package com.ysq.frame;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 获得/改变最高得分类
 * @author Administrator
 *
 */
public class ScoreUtil {
	static File scoreFile;//分数资源文件
	static{
		String scorePath = System.getProperty("user.dir") + "/snakeScore.properties";
		scoreFile = new File(scorePath);
	}
	
	/**
	 * 获得最高分
	 * @return
	 */
	public static int getHighestScore(){
		int score = 0;
		if(scoreFile.exists()){
			BufferedReader br = null;
			String scoreStr = "";
			try {
				br = new BufferedReader(new FileReader(scoreFile));
				scoreStr = br.readLine();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				score = Integer.parseInt(scoreStr);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				//如果分数有误，设置初始值 0
				setHighestScore(0);
				score = 0;
			}
		}else{
			setHighestScore(score);
		}
		return score;
	}
	
	/**
	 * 设置最高分
	 */
	public static void setHighestScore(int score){
		FileWriter fw = null;
		//ScoreUtil.class.getResource();
		try {
			fw = new FileWriter(scoreFile);
			fw.write("" + score);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(fw != null){
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
